package pharmacy.model;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import pharmacy.Pharmacy;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Farmacia {
    private final String nome;
    private final String href;
    private final String[] contato;

    private Farmacia(Element element) {
        Element a = element.select("strong a").get(0);
        nome = a.text();
        href = a.attr("href");
        Elements elements = element.select("p");
        List<String> strings = new ArrayList<>();
        for(Element p : elements){
            strings.add(p.text());
        }
        contato = strings.toArray(new String[strings.size()]);
    }

    public String getHref() {
        return href;
    }

    public String getNome() {
        return nome;
    }

    public String[] getContato() {
        return contato;
    }

    public static Farmacias[] load(Concelho concelho) throws IOException {
        Farmacias[] farmacias = new Farmacias[]{new Farmacias(), new Farmacias()};

        System.out.println("File doesn't exist. Loading from site...");

        String url = Pharmacy.URL + concelho.getHref();
        System.out.println(url);
        Document document = Jsoup.connect(url).get();

        final Elements select = document.select(".blocoFarm");
        System.out.println(select.size());

        parse(farmacias[0], select.get(0));
        parse(farmacias[1], select.get(1));

        return farmacias;
    }

    private static void parse(Farmacias farmacias, Element parent) {
        final Elements elements = parent.select(".farmacia");

        for (Element child : elements)
            farmacias.add(new Farmacia(child));
    }
}
